require 'hpricot'
require 'open-uri'
module VideoUtils
  
  UNKNOWN = 0
  YOUTUBE = 1
  
  class VideoInfoExtracter
    attr_reader :description, :title
    @url =""
    def initialize(url)
      @url = url
    end
    
    def processed?
      #<meta name="title" content="OneRepublic/Timbaland - Apologize (Boyce Avenue piano acoustic cover) on iTunes">
      #<meta name="description" content="Facebookhttp://www.facebook.com/boyceavenueMySpacehttp://www.myspace.com/boyceavenueTwitterhttp://www.twitter.com/boyceavenueiTuneshttp://www.itunes.com/boyc..."> 
      @title =""
      @description=""
      raise ArgumentError unless @url 
      doc = Hpricot(open(@url))
      title_el = doc.search("//meta[@name='title']")
      @title=title_el.first.attributes['content'] if title_el and title_el.first 
      content_el = doc.search("//meta[@name='description']")
      @description=content_el.first.attributes['content'] if content_el and content_el.first 
      return true
    rescue
      return false
    end
    
  end
  class VideoUtils
    
    
    ## Find the service serving the video
    ## Now only supports youtube 
    def self.find_video_service(url)
      service = UNKNOWN
      #find out if the service is youtube
      service = YOUTUBE if url and url.match(/youtube.com/i)
      service
    end
    
    def self.find_video_id(url, service )
      video_id = nil
      case service
        when YOUTUBE
        video_id = VideoUtils.find_youtube_video_id(url)   
      end
      video_id
    end
    
    private 
    def self.find_youtube_video_id(url)
      video_id = nil
      query_string = url.split( '?', 2)[1]
      if query_string
        params = CGI.parse(query_string)
        if params.has_key?("v")
          video_id = params["v"][0]
        end
      end
      
      if video_id and video_id.strip.empty?
        video_id = nil  
      end
      video_id
    end
  end
  
end